<?php

namespace App\Http\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

/**
 * Class Article
 *
 * @method static self articleTagId
 * @mixin Builder
 * @mixin \Illuminate\Database\Query\Builder
 * @package App\Http\Models
 */
class Article extends BosModel
{
    use SafeSave;
    use SoftDeletes;
    protected $dates = ['deleted_at'];

    protected static $unguarded = true;

    protected $bosKeyPrefix = 'bym-admin/article/';

    protected $table = 'articles';

    public function setThumbAttribute($data)
    {
        if ($data) {
            $bosKey = $this->uploadImages($data, 'article/thumb/');
            $this->attributes['thumb'] = $bosKey;
        }
    }

    public function getThumbAttribute()
    {
        if ($this->attributes['thumb']) {
            return $this->getUrl($this->attributes['thumb']);
        }
    }

    public function setBannerAttribute($data)
    {
        if ($data && ! is_string($data)) {
            $bosKey = $this->uploadImages($data, 'article/banner/');
            $this->attributes['banner'] = $bosKey;
        } else {
            $this->attributes['banner'] = $data;
        }
    }

    public function getBannerAttribute()
    {
        if ($this->attributes['banner']) {
            return $this->getUrl($this->attributes['banner']);
        }
    }

    public function setCarouselFigureAttribute($data)
    {
        if ($data) {
            $bosKey = $this->uploadImages($data, 'article/carousel_figure/');
            $this->attributes['carousel_figure'] = $bosKey;
        }
    }

    public function getCarouselFigureAttribute()
    {

        if ($this->attributes['carousel_figure']) {
            return $this->getUrl($this->attributes['carousel_figure']);
        }

    }

    public function setCompanyThumbAttribute($data)
    {
        if ($data) {
            $bosKey = $this->uploadImages($data, 'article/company_thumb/');
            $this->attributes['company_thumb'] = $bosKey;
        }
    }

    public function getCompanyThumbAttribute()
    {

        if ($this->attributes['company_thumb']) {
            return $this->getUrl($this->attributes['company_thumb']);
        }

    }

    /**
     * @used-by articleTagId
     *
     * @param $query
     * @param $tag_id
     *
     * @return mixed
     */
    public function scopeArticleTagId(Builder $query, $tag_id)
    {
        $tag = ArticleTag::find($tag_id);

        $article_ids = $tag->articles->pluck('id');

        if (! count($article_ids)) {
            $article_ids = DB::table('article_pivot_tag')->whereIn('article_tag_id', $tag->tags->pluck('id'))->pluck('article_id');
        }

        return $query->whereIn('id', $article_ids);
    }

    public function articleTags()
    {
        return $this->belongsToMany(ArticleTag::class, 'article_pivot_tag', 'article_id', 'article_tag_id');
    }

}
